<template>
  <div class="admin-settings">
    <el-page-header @back="goBack">
      <template #content>
        <span class="text-large font-600 mr-3">系统配置</span>
      </template>
    </el-page-header>

    <el-card style="margin-top: 20px;">
      <template #header>
        <div style="display: flex; align-items: center;">
          <el-icon style="margin-right: 8px;"><Setting /></el-icon>
          <span>推荐算法权重配置</span>
        </div>
      </template>

      <el-form :model="settings" label-width="200px" style="max-width: 800px;">
        <el-form-item label="热度权重">
          <el-slider
            v-model="settings.popularity_weight"
            :min="0"
            :max="100"
            :step="1"
            show-input
            :format-tooltip="formatTooltip"
          />
          <span style="margin-left: 10px; color: #909399;">{{ settings.popularity_weight }}%</span>
        </el-form-item>

        <el-form-item label="评分权重">
          <el-slider
            v-model="settings.rating_weight"
            :min="0"
            :max="100"
            :step="1"
            show-input
            :format-tooltip="formatTooltip"
          />
          <span style="margin-left: 10px; color: #909399;">{{ settings.rating_weight }}%</span>
        </el-form-item>

        <el-form-item label="价格权重">
          <el-slider
            v-model="settings.price_weight"
            :min="0"
            :max="100"
            :step="1"
            show-input
            :format-tooltip="formatTooltip"
          />
          <span style="margin-left: 10px; color: #909399;">{{ settings.price_weight }}%</span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Check" @click="handleSave" :loading="saving">
            保存配置
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">重置为默认值</el-button>
        </el-form-item>
      </el-form>

      <el-alert
        type="info"
        :closable="false"
        style="margin-top: 20px;"
      >
        <template #default>
          <p>权重总和建议为100%，系统会自动归一化处理。</p>
          <p>权重越大，该因素在推荐算法中的影响越大。</p>
        </template>
      </el-alert>
    </el-card>

    <el-card style="margin-top: 20px;">
      <template #header>
        <div style="display: flex; align-items: center;">
          <el-icon style="margin-right: 8px;"><Tools /></el-icon>
          <span>系统参数配置</span>
        </div>
      </template>

      <el-form :model="systemParams" label-width="200px" style="max-width: 800px;">
        <el-form-item label="默认每页显示数量">
          <el-input-number
            v-model="systemParams.default_page_size"
            :min="10"
            :max="100"
            :step="10"
          />
        </el-form-item>

        <el-form-item label="路线规划最大景点数">
          <el-input-number
            v-model="systemParams.max_attractions_per_route"
            :min="5"
            :max="50"
            :step="5"
          />
        </el-form-item>

        <el-form-item label="推荐路线数量">
          <el-input-number
            v-model="systemParams.recommended_routes_count"
            :min="5"
            :max="50"
            :step="5"
          />
        </el-form-item>

        <el-form-item label="缓存过期时间（分钟）">
          <el-input-number
            v-model="systemParams.cache_expire_minutes"
            :min="5"
            :max="1440"
            :step="5"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Check" @click="handleSaveParams" :loading="saving">
            保存配置
          </el-button>
          <el-button :icon="Refresh" @click="handleResetParams">重置为默认值</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, Tools, Check, Refresh } from '@element-plus/icons-vue'
import logger from '../utils/logger'

export default {
  name: 'AdminSettings',
  components: {
    Setting,
    Tools
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const saving = ref(false)

    const settings = ref({
      popularity_weight: 40,
      rating_weight: 40,
      price_weight: 20
    })

    const systemParams = ref({
      default_page_size: 20,
      max_attractions_per_route: 20,
      recommended_routes_count: 10,
      cache_expire_minutes: 30
    })

    const defaultSettings = {
      popularity_weight: 40,
      rating_weight: 40,
      price_weight: 20
    }

    const defaultParams = {
      default_page_size: 20,
      max_attractions_per_route: 20,
      recommended_routes_count: 10,
      cache_expire_minutes: 30
    }

    const isAdmin = computed(() => store.getters.isAdmin)

    const formatTooltip = (val) => {
      return `${val}%`
    }

    const handleSave = async () => {
      // 验证权重总和
      const total = settings.value.popularity_weight + settings.value.rating_weight + settings.value.price_weight
      if (total === 0) {
        ElMessage.warning('权重总和不能为0')
        return
      }

      saving.value = true
      try {
        // 保存到本地存储（当前使用localStorage，后续可扩展为API调用）
        localStorage.setItem('recommendation_weights', JSON.stringify(settings.value))
        localStorage.setItem('recommendation_weights_updated_at', new Date().toISOString())
        
        // 模拟API调用延迟，提供更好的用户体验
        await new Promise(resolve => setTimeout(resolve, 300))
        
        ElMessage.success('推荐算法权重配置保存成功')
      } catch (error) {
        logger.error('保存配置失败:', error)
        ElMessage.error('保存配置失败，请重试')
      } finally {
        saving.value = false
      }
    }

    const handleReset = () => {
      ElMessageBox.confirm('确定要重置为默认值吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        settings.value = { ...defaultSettings }
        ElMessage.success('已重置为默认值')
      }).catch(() => {})
    }

    const handleSaveParams = async () => {
      // 验证参数范围
      if (systemParams.value.default_page_size < 10 || systemParams.value.default_page_size > 100) {
        ElMessage.warning('每页显示数量应在10-100之间')
        return
      }
      if (systemParams.value.max_attractions_per_route < 5 || systemParams.value.max_attractions_per_route > 50) {
        ElMessage.warning('路线规划最大景点数应在5-50之间')
        return
      }

      saving.value = true
      try {
        // 保存到本地存储（当前使用localStorage，后续可扩展为API调用）
        localStorage.setItem('system_params', JSON.stringify(systemParams.value))
        localStorage.setItem('system_params_updated_at', new Date().toISOString())
        
        // 模拟API调用延迟，提供更好的用户体验
        await new Promise(resolve => setTimeout(resolve, 300))
        
        ElMessage.success('系统参数配置保存成功')
      } catch (error) {
        logger.error('保存配置失败:', error)
        ElMessage.error('保存配置失败，请重试')
      } finally {
        saving.value = false
      }
    }

    const handleResetParams = () => {
      ElMessageBox.confirm('确定要重置为默认值吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        systemParams.value = { ...defaultParams }
        ElMessage.success('已重置为默认值')
      }).catch(() => {})
    }

    const loadSettings = () => {
      // 从本地存储加载配置
      const savedWeights = localStorage.getItem('recommendation_weights')
      if (savedWeights) {
        try {
          const parsed = JSON.parse(savedWeights)
          // 验证数据有效性
          if (parsed.popularity_weight !== undefined && 
              parsed.rating_weight !== undefined && 
              parsed.price_weight !== undefined) {
            settings.value = { ...defaultSettings, ...parsed }
          }
        } catch (e) {
          logger.error('加载推荐权重配置失败:', e)
          // 如果加载失败，使用默认值
        }
      }

      const savedParams = localStorage.getItem('system_params')
      if (savedParams) {
        try {
          const parsed = JSON.parse(savedParams)
          // 验证数据有效性
          if (parsed.default_page_size !== undefined && 
              parsed.max_attractions_per_route !== undefined &&
              parsed.recommended_routes_count !== undefined &&
              parsed.cache_expire_minutes !== undefined) {
            systemParams.value = { ...defaultParams, ...parsed }
          }
        } catch (e) {
          logger.error('加载系统参数配置失败:', e)
          // 如果加载失败，使用默认值
        }
      }
    }

    const goBack = () => {
      router.push('/admin')
    }

    onMounted(() => {
      if (!isAdmin.value) {
        ElMessage.error('您没有管理员权限')
        router.push('/')
        return
      }
      loadSettings()
    })

    return {
      settings,
      systemParams,
      saving,
      formatTooltip,
      handleSave,
      handleReset,
      handleSaveParams,
      handleResetParams,
      goBack,
      Check,
      Refresh
    }
  }
}
</script>

<style scoped>
.admin-settings {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
}

:deep(.el-card) {
  border-radius: 12px;
  border: none;
}

:deep(.el-slider) {
  flex: 1;
}
</style>

